package com.qishanor.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qishanor.framework.base.DictVO;
import com.qishanor.framework.util.R;
import com.qishanor.system.model.SysRole;
import com.qishanor.system.model.SysUserRole;
import com.qishanor.system.model.vo.SysRoleVo;
import com.qishanor.system.service.SysRoleService;
import com.qishanor.system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description: 角色管理
 * @author: 周振林
 * @date: 2022-04-15
 * @Copyright: 博客：http://www.zhouzhenlin.com - 沉淀、分享、成长、让自己和他人都有所收获
 **/

@RestController
@RequestMapping("/api/sys/role")
@SaCheckLogin
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 获取角色列表
     * @return 角色列表
     */
    @GetMapping("/role_dict")
    public R getList()
    {
        List<DictVO> results=sysRoleService.list(Wrappers.emptyWrapper())
                .stream().map(u->new DictVO<Integer>(u.getName(),u.getId().toString())).collect(Collectors.toList());
        return R.ok(results);
    }

    @GetMapping("/user/{userId}")
    public R getRoleByUserId(@PathVariable Integer userId){
        List<Object> lists=sysUserRoleService.listObjs(Wrappers.lambdaQuery(SysUserRole.class).select(SysUserRole::getRoleId).eq(SysUserRole::getUserId,userId));

        return R.ok(lists);
    }

    @GetMapping("/page")
    @SaCheckPermission("sys_role_view")
    public R page(Page page, SysRole sysRole){
        return  R.ok(sysRoleService.page(page, Wrappers.lambdaQuery(sysRole)));
    }

    @PostMapping
    @SaCheckPermission("sys_role_add")
    public R save(@RequestBody SysRole sysRole){
        return R.ok(sysRoleService.save(sysRole));
    }

    @PutMapping
    @SaCheckPermission("sys_role_edit")
    public R updateById(@RequestBody SysRole sysRole){
        return R.ok(sysRoleService.updateById(sysRole));
    }

    @DeleteMapping("/{id}")
    @SaCheckPermission("sys_role_del")
    public R removeById(@PathVariable Integer id){
        return R.ok(sysRoleService.removeById(id));
    }


    /**
     * 更新角色菜单
     * @return success、false
     */
    @PutMapping("/menu")
    @SaCheckPermission("sys_role_perm")
    public R saveRoleMenus(@RequestBody SysRoleVo sysRoleVo) {
        return R.ok(sysRoleService.updateRoleMenus(sysRoleVo.getRoleId(), sysRoleVo.getMenuIds()));
    }

}
